<template>
  <q-page class="prod-page column no-wrap" style="background-color: #fff">
    <header class="flex items-center q-pr-md q-pl-sm q-py-sm" style="background-color: rgb(255, 249, 234)">
      <div class="center">
        <q-icon name="volume_up" style="color: rgb(255, 154, 67); font-size: 21px" />
      </div>
      <div class="flex-1" style="width: 20px">
        <Marquee :loading="false">
          <div class="" style="color: rgb(255, 154, 67)">
            警示:金耀花温馨提示本平台不会有任何境外电话,请不要接听境外电话,谨防电信诈骗!如有疑惑请拨打客服电话:4006890220
          </div>
        </Marquee>
      </div>
    </header>

    <section class="q-px-md flex-1 column no-wrap" style="height: 200px">
      <!-- <div class="flex items-end q-mt-md" v-if="checkUser?.pushSuccess || showList.length > 0">
        <img src="~/assets/images/prod/image2.png" alt="image2" class="block q-mr-sm" style="width: 70px" />
        <div>
          <div style="font-weight: bold; font-size: 18px">恭喜您，匹配成功！</div>
          <div class="flex items-center q-mt-xs">
            <div
              style="background: #fff4e7; border-radius: 6px"
              class="q-py-xs q-px-sm flex items-center q-mr-sm"
            >
              <div
                class="q-mr-xs"
                v-if="checkUser?.companyLogo"
                style="
                  width: 25px;
                  height: 25px;
                  border-radius: 6px;
                  background-size: cover;
                  background-position: center;
                "
                :style="{ backgroundImage: `url(${checkUser?.companyLogo})` }"
              ></div>
              <div class="" style="font-size: 16px">
                {{ checkUser?.pushSuccess ? checkUser.infoName : showList[0].productName }}
              </div>
            </div>

            <div
              @click="submitHandler"
              style="color: #ffad13; text-decoration-line: underline; font-weight: bold; font-size: 16px"
              class=""
            >
              点击授权
            </div>
          </div>
        </div>
      </div> -->

      <!-- 顶部机构banner -->
      <div
        class="q-mt-md"
        v-if="checkUser"
        style="padding: 12px; background-color: #f6f6f6; border-radius: 8px"
      >
        <div class="flex items-start no-wrap">
          <div
            class=""
            v-if="checkUser?.companyLogo"
            style="
              width: 45px;
              height: 45px;
              min-width: 45px;
              border-radius: 8px;
              background-size: cover;
              background-position: center;
              margin-right: 10px;
            "
            :style="{ backgroundImage: `url(${checkUser?.companyLogo})` }"
          ></div>
          <div>
            <div>
              <span style="font-size: 15px; font-weight: bold"
                >你好，<span class="text-primary">{{
                  checkUser?.pushSuccess ? checkUser.infoName : showList[0].productName
                }}</span>
                出具的预估额度为：</span
              >
              <span style="font-size: 18px; font-weight: bold">{{
                checkUser?.pushSuccess
                  ? Number(checkUser.maxLoanAmount || 0).toLocaleString()
                  : Number(showList[0]?.lnAmount.split('-')[1] || 0).toLocaleString()
              }}</span
              ><span style="font-size: 12px; color: #999">&nbsp;(元)</span>
            </div>
          </div>
        </div>

        <div style="background-color: #d8d8d8; height: 1px; margin: 8px 0px 12px" class=""></div>

        <div class="flex items-center justify-between" style="font-size: 12px">
          <div class="flex items-center">
            <img
              src="~/assets/images/public/ok_select.png"
              alt="ok_select"
              class="block q-mr-xs"
              style="width: 13px"
            />
            <div>分期灵活</div>
          </div>
          <div class="flex items-center">
            <img
              src="~/assets/images/public/ok_select.png"
              alt="ok_select"
              class="block q-mr-xs"
              style="width: 13px"
            />
            <div>大额低息</div>
          </div>
          <div class="flex items-center">
            <img
              src="~/assets/images/public/ok_select.png"
              alt="ok_select"
              class="block q-mr-xs"
              style="width: 13px"
            />
            <div>随借随还</div>
          </div>
        </div>

        <q-btn
          color="primary"
          unelevated
          label="确认额度"
          class="full-width"
          style="border-radius: 8px; font-size: 16px; margin-top: 12px"
          padding="sm md"
          @click="submitHandler"
        />

        <div class="q-mt-sm">
          <span class="q-mr-xs" style="vertical-align: text-top" @click="isAgree = !isAgree">
            <img v-if="!isAgree" src="~/assets/images/public/nu_select.png" style="width: 14px" />
            <img v-else src="~/assets/images/public/ok_select.png" style="width: 14px" />
          </span>
          <span style="color: #222; font-size: 13px"
            ><span @click="isAgree = true">我已阅读并同意</span
            ><span
              class="text-primary"
              @click="
                useWebView().goTo('个人信息共享授权协议', '\\static/protocol/个人信息共享授权协议.html')
              "
              >《个人信息共享授权协议》</span
            ></span
          >
        </div>
      </div>

      <section
        v-if="!!showList.length"
        class="flex-1 q-mt-md column no-wrap"
        style="padding: 10px; height: 200px; border-radius: 12px"
        :style="{ background: '#fff4e7' }"
      >
        <div style="font-size: 14px; font-weight: 600" class="q-mb-sm">推荐机构</div>
        <div class="flex-1" style="height: 180px">
          <div class="row q-col-gutter-sm">
            <div class="col-6" v-for="(item, index) in showList" :key="index">
              <div class="prod-box">
                <div style="padding: 10px; background-color: #fff; border-radius: 8px">
                  <div class="flex items-center no-wrap">
                    <div
                      class="q-mr-xs"
                      style="
                        width: 18px;
                        height: 18px;
                        border-radius: 99999px;
                        background-size: cover;
                        background-position: center;
                      "
                      :style="{ backgroundImage: `url(${item.logoUrl})` }"
                    ></div>
                    <div
                      class="flex-1 hide-scrollbar"
                      style="width: 50px; overflow-x: auto; white-space: nowrap"
                    >
                      {{ item.productName }}
                    </div>
                  </div>
                  <div style="color: #999999; font-size: 12px" class="q-mt-sm">最高可借(元)</div>
                  <div style="color: #222; font-size: 24px; font-weight: bold">
                    {{ Number(item.lnAmount.split('-')[1] || 0).toLocaleString() }}
                  </div>
                  <div style="color: #999999; font-size: 12px" class="q-mt-xs">借款期限</div>
                  <div class="font-DINAlternate" style="color: #ff1e4a; font-size: 15px; font-weight: bold">
                    {{ item.lnPeriod }}月
                  </div>

                  <div class="q-mt-sm q-px-sm">
                    <q-btn
                      color="primary"
                      padding="xs md"
                      unelevated
                      class="full-width"
                      rounded
                      style=""
                      @click="gotoProd(prodTwoList.length ? 3 : 2, item)"
                      label="去申请"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      <div v-else class="flex-1" style="height: 20px"></div>

      <div
        @click="router.push({ path: '/feedback', query: route.query })"
        style="font-size: 13px; color: #ffad13"
        class="text-center q-mt-lg q-mb-xs"
      >
        投诉与建议
      </div>

      <div style="font-size: 12px; color: #999999" class="text-center q-mb-lg">
        <div>客服电话：4006890220</div>
        <div>客服在线时间:周一至周五 9:30-18:30</div>
      </div>
    </section>
    <ProdDialog ref="ProdDialogRef" />
    <Protocol ref="ProtocolRef" />
  </q-page>
</template>

<script setup lang="ts">
import { getProdUnionResultApi, prodClickCountApi, prodInfoListApi } from 'src/api/prod';
import { showLoadingToast, showToast } from 'vant/lib/toast';
import { onMounted, ref } from 'vue';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { onUnmounted } from 'vue';
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { CheckUserRes, ProdItem, ResType, gotoProd } from './prodList';
import ProdDialog from './dialog/ProdDialog.vue';
import { ProdDialogInstance } from './dialog/ProdDialog';
import { useMechanismStore } from 'src/stores/mechanism-store';
import {
  againCheckUserApi,
  approveClickCountApi,
  pushToMerchantApi,
  waitApproveListApi,
} from 'src/api/merchant';
import { MatchResult, MatchResultOrderItemList } from 'src/types/matchResult';
import Protocol from './dialog/Protocol.vue';
import { ProtocolInstance } from './dialog/Protocol';
import { testMatchResult } from '../mechanism/mock';
import { debounce } from 'lodash';
import Marquee from 'src/components/Marquee.vue';
import logoPng from 'src/assets/images/public/logo.png';
import CryptoJS from 'crypto-js';
import { useWebView } from '../webview/webview';

const router = useRouter();
const route = useRoute();

const isAgree = ref(false);

const ProdDialogRef = ref<ProdDialogInstance>();
const ProtocolRef = ref<ProtocolInstance>();

const prodOneList = ref<ProdItem[]>([]);
const prodTwoList = ref<ProdItem[]>([]);
const approveList = ref<MatchResultOrderItemList[]>([]);

const showExt = computed(() => {
  return prodTwoList.value?.length ? 3 : 2;
});
const showList = computed(() => {
  return prodTwoList.value?.length ? prodTwoList.value : prodOneList.value;
});

const randomProd = computed(() => {
  if (!prodOneList.value?.length) return null;
  // const list = (() => {
  //   if (prodOneList.value.length && prodTwoList.value.length) {
  //     return [prodOneList.value, prodTwoList.value][Math.floor(Math.random() * 2)]
  //   }
  //   return showList.value
  // })()
  const index = Math.floor(Math.random() * prodOneList.value.length);
  return prodOneList.value[index];
});

const dialogShowHandler = () => {
  if (ProdDialogRef.value?.getShow()) return;
  if (approveList.value.length) {
    const index = Math.floor(Math.random() * approveList.value.length);
    ProdDialogRef.value?.showApprove(approveList.value[index]);
    return;
  }
  if (randomProd.value) {
    ProdDialogRef.value?.show(randomProd.value);
  }
};

const checkUser = ref<CheckUserRes>();

const initApproveList = async () => {
  const { orderId } = useMechanismStore();
  if (!orderId) return;
  const res = await waitApproveListApi<MatchResult>({ orderNo: orderId });
  approveList.value = res.data.orderItemList;

  // approveList.value = testMatchResult.orderItemList;

  dialogShowHandler();
};

const initAgainCheckData = async () => {
  const res = await againCheckUserApi<CheckUserRes>({});
  res.data && (checkUser.value = res.data);
};

const showProdDialog = debounce(() => {
  if (randomProd.value) {
    ProdDialogRef.value?.show(randomProd.value);
  }
}, 100);

const approveClickHandler = async (item: MatchResultOrderItemList) => {
  if (item.protocolUrl) {
    ProtocolRef.value?.show(item);
    return;
  }
  const { orderId } = useMechanismStore();
  await approveClickCountApi({ orderNo: orderId, orderItemId: item.orderItemId });
  if (!item.approveUrl) return;
  window.location.href = item.approveUrl;
};

const againCheckClickHandler = async (item: CheckUserRes) => {
  if (item.protocolUrl) {
    // ProtocolRef.value?.showAgainCheck(item);
    const dataTemp = {
      orderNo: item.pushOrderNo,
      logoUrl: item.companyLogo,
      mainTitle: item.infoName,
      compantName: item.companyName,
      minRate: item.minRate,
      protocolUrl: item.protocolUrl,
    };
    const dataUrl = CryptoJS.enc.Base64url.stringify(CryptoJS.enc.Utf8.parse(JSON.stringify(dataTemp)));
    console.log(dataUrl);
    router.push({ path: 'protocol', query: { data: dataUrl } });
    return;
  }
  const toast = showLoadingToast({
    iconSize: 50,
    forbidClick: true,
    duration: 0,
  });

  await pushToMerchantApi({ orderNo: item.pushOrderNo });
  toast.close();
  router.replace({ path: 'evaluateAuth', query: { ...route.query, isToProdList: '1' } });
};

const submitHandler = debounce(() => {
  if (!isAgree.value) {
    return showToast('请先同意协议');
  }
  if (checkUser.value?.pushSuccess) {
    return againCheckClickHandler(checkUser.value!);
  }
  gotoProd(showExt.value, showList.value[0]);
}, 16);

const initData = async () => {
  const toast = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  try {
    await initAgainCheckData();
    const [resOne, resTwo] = await Promise.all([
      prodInfoListApi<ResType>({ sceneId: 2 }),
      prodInfoListApi<ResType>({ sceneId: 3 }),
    ]);
    toast.close();
    prodOneList.value = resOne.data.dataList;
    prodTwoList.value = resTwo.data.dataList;
    dialogShowHandler();
  } catch (error) {
    toast.close();
  }
};

const popstateHandler = (e: PopStateEvent) => {
  showProdDialog();
  setTimeout(() => {
    window.history.pushState({ ProdListPage: true }, 'ProdListPage', window.location.href);
  });
};

const goToPage = (path: string) => {
  window.location.href = path;
};

onMounted(() => {
  window.history.pushState({ ProdListPage: true }, 'ProdListPage', window.location.href);
  window.addEventListener('popstate', popstateHandler);
  window.addEventListener('focus', showProdDialog);
});

onUnmounted(() => {
  window.removeEventListener('popstate', popstateHandler);
  window.removeEventListener('focus', showProdDialog);
});

initData();
// initApproveList();
</script>

<style lang="scss" scoped>
.mechanism-card {
  background: rgb(254, 242, 228);
  background: linear-gradient(180deg, #fef2e4 0%, #ffffffb3 100%);
  border: 1px solid #fff;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  .mark {
    position: absolute;
    right: 0;
    top: 0;
    .mark-text {
      background: #ffd101;
      border-radius: 0px 0px 0px 8px;
      font-size: 12px;
      font-weight: bold;
      padding: 2px 10px;
    }
  }
}
.marquee {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  span {
    display: inline-block;
    animation: marquee 10s linear infinite;
  }
}
@keyframes marquee {
  from {
    transform: translateX(50%);
  }
  to {
    transform: translateX(-100%);
  }
}

.prod-page {
  // background-image: url(src/assets/images/prod/bg.png);
  // background-size: 100% auto;
  // background-repeat: no-repeat;
}
.header {
  position: relative;
  z-index: 1;
  max-width: 100vw;
  .bg {
    position: absolute;
    z-index: 0;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: linear-gradient(136deg, #ff8854 0%, #ffb270 100%);
    opacity: 0.3;
  }
  .content {
    position: relative;
    z-index: 2;
  }
}

.prod-item {
  background-image: url(src/assets/images/prod/item-bg.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 8px;
  overflow: hidden;
  .mark {
    background-image: url(src/assets/images/prod/mark.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    padding: 6px 24px 14px 12px;
  }
  .tag {
    padding: 1px 6px;
    border-radius: 6px;
    margin-left: -2px;
    margin-bottom: 4px;
    color: #fe6c09;
    font-size: 12px;
    // white-space: nowrap;
    border: 1px solid rgba($color: #fe6c0b, $alpha: 0.4);
  }
}

.mechanism-item {
  background-image: url(src/assets/images/prod/item-bg.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 8px;
  overflow: hidden;
  .mark {
    background-image: url(src/assets/images/prod/mark.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    padding: 6px 24px 14px 12px;
  }
  .mark-lg {
    background-size: 105% 100%;
  }
  .tag {
    padding: 1px 6px;
    border-radius: 6px;
    margin-left: -2px;
    margin-bottom: 4px;
    color: #fe6c09;
    font-size: 12px;
    // white-space: nowrap;
    border: 1px solid rgba($color: #fe6c0b, $alpha: 0.4);
  }
}
</style>
